const Controller = require('../prototype/Controller')
const { models } = require('../model')
const fflate = require('fflate')
const { ObjectId } = require('mongodb')

// eslint-disable-next-line no-unused-vars
function compressStrToBase64 (utf8Str) {
  const buf = fflate.strToU8(utf8Str)
  const compressedUint8 = fflate.compressSync(buf, {
    level: 6,
    mem: 8
  })
  return Buffer.from(compressedUint8).toString('base64')
}

function decompressBase64ToStr (base64Str) {
  const compressed = Buffer.from(base64Str, 'base64')
  const decompressed = fflate.decompressSync(compressed)
  return fflate.strFromU8(decompressed)
}

class UserStorageController extends Controller {
  constructor () {
    super({ model: models.UserStorage })
  }

  saveStorage () {
    return async (ctx) => {
      const user = ctx._user
      if (!user) {
        return ctx.wrapper.error('AUTH_ERROR', '注册登陆后才可以使用云端数据')
      }
      const {
        type,
        data,
        tag
      } = ctx.request.body
      if (!type) {
        return ctx.wrapper.error('PARAMETERS_ERROR', '数据类型异常')
      }
      if (!data) {
        return ctx.wrapper.error('PARAMETERS_ERROR', '数据内容异常')
      }
      const docUpdate = {
        data: data,
        userName: user.name
      }
      const query = {
        userId: user._id,
        type: type
      }
      if (tag) {
        query.tag = tag
        docUpdate.tag = tag
      }
      const result = await this.model.updateOne(query, {
        $set: docUpdate
      }, { upsert: true })
      return ctx.wrapper.succ(result)
    }
  }

  loadStorage () {
    return async (ctx) => {
      const user = ctx._user
      if (!user) {
        return ctx.wrapper.error('AUTH_ERROR', '注册登陆后才可以使用云端数据')
      }
      const {
        type,
        tag
      } = ctx.request.body
      if (!type) {
        return ctx.wrapper.error('PARAMETERS_ERROR', '数据类型异常')
      }
      const query = {
        userId: user._id,
        type: type
      }
      if (tag) {
        query.tag = tag
      }
      const result = await this.model.findOne(query)
      return ctx.wrapper.succ(result)
    }
  }

  // 内部使用 : 解析已压缩用户数据
  loadDeflateStorage () {
    return async (ctx) => {
      const {
        userId,
        type
      } = ctx.request.body
      if (!type) {
        return ctx.wrapper.error('PARAMETERS_ERROR', '数据类型异常')
      }
      const result = await this.model.findOne({
        userId: userId,
        type: type
      })
      result.data = decompressBase64ToStr(result.data)
      return ctx.wrapper.succ(result)
    }
  }

  // 用户工作台数据更新
  updateWorkbenches () {
    return async (ctx) => {
      const user = ctx._user
      if (!user) {
        return ctx.wrapper.error('AUTH_ERROR', '注册登陆后才可以使用云端数据')
      }
      const { update } = ctx.request.body
      const result = await models.User.updateById(user._id, {
        $set: {
          workbenches: update
        }
      })
      return ctx.wrapper.succ(result)
    }
  }

  // 获取分享列表
  async getSharePanels () {
    return async (ctx) => {
      const user = ctx._user
      const panels = await models.SharePanel.find({
        userId: user._id
      }).toArray()
      return ctx.wrapper(panels)
    }
  }

  // 创建分享面板
  createSharePanel () {
    return async (ctx) => {
      const user = ctx._user
      const { id } = ctx.request.body
      const panel = await models.UserStorage.findOne({
        userId: user._id,
        tag: id
      })
      if (!panel) {
        throw '分享面板数据不存在'
      }
      const result = await models.SharePanel.insertOne({
        userId: user._id,
        userName: user.name,
        data: panel.data
      })
      return ctx.wrapper({
        id: result.insertedId
      })
    }
  }

  // 更新分享面板
  updateSharePanel () {
    return async (ctx) => {
      const user = ctx._user
      const {
        id,
        data
      } = ctx.request.body
      const result = await models.SharePanel.updateOne({
        _id: ObjectId(id),
        userId: user._id
      }, {
        userId: user._id,
        userName: user.name,
        data: data
      })
      return ctx.wrapper(result)
    }
  }
}

module.exports = UserStorageController
